// pages/tiezi-comment/tiezi-comment.js
let userInfo = {}
import formatTime from '../../../../style/formatTime'
const db = wx.cloud.database()
const _ = db.command
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tiezi: {},
    commentList: [],
    tieziId: '',
    dianzan: '',
    // 登录组件是否显示
    loginShow: false,
    // 底部弹出层是否显示
    modalShow: false,
    modalShow1: false,
    id: '',
    openidfb:'',
    openidsd:'',
    isOpen: false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     
    console.log(options)
    this.setData({
      tieziId: options.tieziId
    })

    wx.cloud.callFunction({
      name: 'getOpenid',
      complete: res => {
        this.setData({
          openid: res.result.openid
        })
        var openid = res.result.openid
        db.collection('dianzan').where({
          _id: options.tieziId + openid,
        })
          .get().then((res) => {
            if (res.data == '') {
              this.setData({
                dianzan: false,
                dianzanUrl: "/images/dianzan_2.png" 
              })
            } else {
              this.setData({
                dianzan: res.data[0].dianzan,
                dianzanUrl: "/images/dianzan_1.png" 
              })
            }

          })

      }
    })
    this._getsc()
    this._gettieziDetail()
  },
  jvbao(event){
    wx.navigateTo({
      url: '/pages/index/jvbao/jvbao?tieziid=' + this.data.tiezi._id +'&ip=' + this.data.tiezi.ip +'&openid='+this.data.tiezi._openid+'&nr='+ event.currentTarget.dataset.nr +'&id='+66,
    })
    this.setData({
      modalShow1: false,
    })
  },
  _gettieziDetail() {
    wx.cloud.callFunction({
      name: 'mantie',
      data: {
        tieziId: this.data.tieziId,
        $url: 'detail',
      }
    }).then((res) => {
      let commentList = res.result.commentList.data
      for (let i = 0, len = commentList.length; i < len; i++) {
        commentList[i].createTime = formatTime(new Date(commentList[i].createTime))
        for (let g = 0, len = commentList[i].reply_list.length; g < len; g++) {
        commentList[i].reply_list[g].createTime = formatTime(new Date(commentList[i].reply_list[g].createTime))
      }
      }
      this.setData({
        commentList,
        tiezi: res.result.detail[0],
        len:commentList.length
      })
      console.log(res)
    })
  },
  _getsc(){
    db.collection('shouchang').where({
      tieziId: this.data.tieziId,
    })
      .get().then((res) => {
          this.setData({
            sc:res.data.length,
          })
          this._getscurl()
      })
},
_getscurl(){

db.collection('shouchang').where({
  _id: this.data.tieziId+this.data.openid,
})
  .get().then((res) => {
    if (res.data == '') {
      this.setData({
        scUrl: "/images/wodeshoucang.png" 
      })
    } else {
      this.setData({
        scUrl: "" 
      })
    }
  })
},

onTapTosc:function ()  {
  wx.showLoading({
    title: '收藏中',
    mask: true,
  })
  db.collection('shouchang').add({
    data: {
      _id:this.data.tieziId+this.data.openid,
      content: this.data.tiezi.content,
      createTime: db.serverDate(),
      tieziId: this.data.tieziId,
      nickName: this.data.tiezi.nickName,
      avatarUrl: this.data.tiezi.avatarUrl,
      img: this.data.tiezi.img,
      ip: 222
    }
  }).then((res) => {
    wx.hideLoading()
    wx.showToast({
      title: '收藏成功',
    })
    this.setData({
      scUrl: "" 
    })
    this._gettieziDetail()
    this._getsc()
  }).catch((err) => {
    wx.hideLoading()
  })

},
  onComment() {
    // 判断用户是否授权
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: (res) => {
              userInfo = res.userInfo
              // 显示评论弹出层
              this.setData({
                modalShow: true,
              })
            }
          })
        } else {
          this.setData({
            loginShow: true,
          })
        }
      }
    })
  },

  onLoginsuccess(event) {
    userInfo = event.detail
    // 授权框消失，评论框显示
    this.setData({
      loginShow: false,
    }, () => {
      this.setData({
        modalShow: true,
      })
    })
  },

  onLoginfail() {
    wx.showModal({
      title: '授权用户才能进行评价',
      content: '',
    })
  },
  onSend(event) {
    // console.log(this.data.tiezi.opid)
    // console.log(event)
    // 插入数据库
    let content = event.detail.value.content
    if (content.trim() == '') {
      wx.showModal({
        title: '评论内容不能为空',
        content: '',
      })
      return
    }
    wx.showLoading({
      title: '评论中',
      mask: true,
    })
    db.collection('meitu-pl').add({
      data: {
        content,
        createTime: db.serverDate(),
        tieziId: this.data.tiezi._id,
        nickName: userInfo.nickName,
        avatarUrl: userInfo.avatarUrl,
        ip: 300,
        biaoqian: this.data.tiezi.biaoqian,
        openidsd: this.data.tiezi.opid,
        isOpen: false,
        biaoqian_ming: this.data.tiezi.biaoqian_ming,
        reply_list: [],
      }
    }).then((res) => {
      wx.hideLoading()
      wx.showToast({
        title: '评论成功',
      })
      this.setData({
        modalShow: false,
        content: '',
      })
      this._gettieziDetail()
    })
  },
 // 点击展开
 chooseUnfold: function(e) {
  var key = e.currentTarget.dataset.key;
  var val = e.currentTarget.dataset.value;
  key = key + '.isOpen';
  this.setData({
    [key]: !val
  })
},
onLoginsuccess1(event) {
  userInfo = event.detail
  // 授权框消失，评论框显示
  this.setData({
    loginShow: false,
  }, () => {
    this.setData({
      modalShow1: true,
    })
  })
},
onComment1(event) {
  // 判断用户是否授权
  wx.getSetting({
    success: (res) => {
      if (res.authSetting['scope.userInfo']) {
        wx.getUserInfo({
          success: (res) => {
            userInfo = res.userInfo
            // 显示评论弹出层
            this.setData({
              modalShow1: true,
              id: event.currentTarget.dataset.id,
              mz: event.currentTarget.dataset.mz,
              openidsd:event.currentTarget.dataset.openidsd,
            })
          }
        })
      } else {
        this.setData({
          loginShow: true,
        })
      }
    }
  })
},
onSend1(event) {
  let content = event.detail.value.content;
  let createTime = db.serverDate();
  let nickName = userInfo.nickName;
  let openidfb = this.data.openid;
  let openidsd = this.data.openidsd;
  let mz = this.data.mz;
  if (content.trim() == '') {
    wx.showModal({
      title: '回复内容不能为空',
      content: '',
    })
    return
  }
  wx.showLoading({
    title: '回复中',
    mask: true,
  })
  db.collection('meitu-pl').where({
    _id: this.data.id
  }).update({
    data: {
      reply_list: _.push({
        openidfb:openidfb,
        openidsd:openidsd,
        content: content,
        createTime: createTime,
        nickName: nickName,
        avatarUrl: userInfo.avatarUrl,
        mz: mz,
        tieziId: this.data.tieziId,
        biaoqian_ming: this.data.tiezi.biaoqian_ming,
      }),
    }
  }).then((res) => {
    wx.hideLoading()
    wx.showToast({
      title: '回复成功',
    })
    this.setData({
      modalShow1: false,
      content: '',
      id: '',
      mz: '',
    })
    this._gettieziDetail()
  })

},
    /**
  * 点赞功能
  */
 clickMe: async function () {
  wx.showLoading({
    title: '点赞中...',
  })

  var dianzan1 = this.data.dianzan
    //云函数方式操作

  if (this.data.dianzan==true) {
    wx.cloud.callFunction({
      name: 'dianzan',
      data: {
        dianzan: dianzan1,
        id: this.data.tiezi._id,
        ip:this.data.tiezi.ip,
        $url: 'delzan'
      }
    }).then((res) => {
      // console.log(res.result)
      this.setData({
        dianzanUrl:"/images/dianzan_2.png",
        dianzan: !dianzan1,
      })
      wx.showToast({
        title: '点赞取消',
        icon: 'success',
        duration: 1500
      })
      this._gettieziDetail()
    })
  } else {
    wx.cloud.callFunction({
      name: 'dianzan',
      data: {
        dianzan: !dianzan1,
        id: this.data.tiezi._id,
        ip:this.data.tiezi.ip,
        $url: 'addzan'
      }
    }).then((res) => {
      // console.log(res.result)
      this.setData({
        dianzanUrl:"/images/dianzan_1.png",
        dianzan:!dianzan1
      })
      wx.showToast({
        title: '点赞成功',
        icon: 'success',
        duration: 1500
      })
      this._gettieziDetail()
    })
  }
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const tiezi = this.data.tiezi
    return {
      title: tiezi.content,
      path: `/pages/index/mantie/mantie-nr/mantie-nr?tieziId=${tiezi._id}`,

    }
  }
})